/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  ,	unscr = require('underscore')
  , sio = require('socket.io')
  ,	sql = require('db-mysql');
  
var mysql = require('mysql');
//Setting up the MySQL connection
var db = mysql.createClient({'host':'localhost','port':3306,'user':'root','password':'123','database':'nodejs'});


var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'your secret here' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
  //app.use(express.logger());
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

//app.get('/', routes.index);
app.get('/',function(req, res){
	db.query('SELECT * FROM polls where pid = 1',
		function selectCb(err,results, fields) {
				if (err) {
					throw err;
				}
				res.render('index', { title: 'Node - Express - MySQL Demo' , body: 'Some body text', output: results});
		}
	);
  
});


var io = sio.listen(app);

io.configure(function(){
	io.set('log level',0);
});

io.sockets.on('connection', function (socket) {
	socket.emit('page load', "Reply from server");
	
	socket.on('poll update', function (data) {
		console.log(data);
  });
  
  setInterval(function () {
    db.query('SELECT * FROM polls where pid = 1',
			function selectCb(err,results, fields) {
					if (err) {
						throw err;
					}
			    socket.broadcast.emit('poll update client',results);
			    console.log(results);			    
			}
		);
  }, 10000);
  
});

app.post('/poll-submit',function(req, res){
	var pollresult = req.body['poll-option'];
	var query = '';
	if(!(typeof pollresult === "undefined")){
		query = "UPDATE polls SET value = value + 1 WHERE pid = 1 AND name = '" + pollresult + "'";
		//query = 'SELECT * FROM polls where pid = 1 AND name = \'' + pollresult + '\'';
		db.query(query,
			function selectCb(err,results, fields) {
					if (err) {
						throw err;
					}
			}
		);
	}
	res.redirect('/');
});

app.get('/reset-poll',function(req, res){
	var query = '';
	query = "UPDATE polls SET value = 0 WHERE pid = 1 ";
	//query = 'SELECT * FROM polls where pid = 1 AND name = \'' + pollresult + '\'';
	db.query(query,
		function selectCb(err,results, fields) {
				if (err) {
					throw err;
				}
		}
	);
	res.redirect('/');
});

app.get('/db',function(req,res){
new sql.Database({
    hostname: 'localhost',
    user: 'root',
    password: '123',
    database: 'nodejs'
}).connect(function(error) {
    if (error) {
        return console.log("CONNECTION ERROR: " + error);
    }

    this.query().select('*').from('polls').execute(function(error, rows) {
        if (error) {
        		res.send('ERROR: ' + error);
            return console.log('ERROR: ' + error);
        }
        res.send(rows.length + ' ROWS for the query ' + this.sql());
        console.log(rows.length + ' ROWS');
    });
});
});

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

